import { login, getInfo } from '/@/api/user'
import { addAdmin, updateAdmin} from '/@/api/app'
import { getToken, setToken, removeToken} from '/@/utils/auth'
import router, { resetRouter } from '/@/router'

const state = {
	token: getToken(),
	name: localStorage.yusername,
	roles: [],
	adminRoles: [],
	adminInfo:{}
}
 
const mutations = {
	SET_TOKEN: (state, token) => {
		 
		state.token = token
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
	},
	SET_ADMINROLES: (state, adminRoles) => {
		state.adminRoles = adminRoles
	},
	SET_ADMININFO: (state, adminInfo) => {
		state.adminInfo = adminInfo
},
}

const actions = {
	// user login
	login({ commit }, userInfo) {
		const { username, password } = userInfo
		return new Promise((resolve, reject) => {
			 
			login({ username: username.trim(), password: password })
				.then((response) => {
					console.log(response)
					const { code, message, result: {
						token,username,
					} } = response
					// 保存token到store
					commit('SET_TOKEN', token);
					commit('SET_NAME', username);
					// 保存token到本地
					setToken(token);
					localStorage.yusername = username;
					resolve()
				})
				.catch((error) => {
					reject(error)
				})
		})
	},

	// get user info
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			getInfo()
				.then((response) => {
					const { code, message, result: {
						list
					}  } = response
					 
					if (!list || list.length <= 0) {
						reject('用户角色信息不能为空')
					}
					// 保存用户信息到store
					commit('SET_ROLES', list)
					
					resolve(list);
				})
				.catch((error) => {
					reject(error)
				})
		})
	},

	// user logout
	logout({ commit, state, dispatch }) {
		return new Promise((resolve, reject) => {
			// 退出登录，删除信息
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeToken()
			// resetRouter()
			resolve()
		})
	},

	// remove token
	resetToken({ commit }) {
		return new Promise((resolve) => {
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeToken()
			resolve()
		})
	},
	adminRoles({ commit }) {
		return new Promise((resolve, reject) => {
			addAdmin().then((res) => {
				const { code,
					message,
					result: {
						list: {
							roleList
						}
					}
				} = res;
				// 保存用户信息到store
				commit('SET_ADMINROLES', roleList)
				resolve(roleList);
			}).catch((error) => {
				reject(error)
			})
		 
		})
	},
	adminInfo({ commit },params) {
		return new Promise((resolve, reject) => {
			updateAdmin(params.id).then((res) => {
				console.log(res)
				const { code,
					message,
					result: {
						info,
						roleList
					 
					}
				} = res;
				// 保存用户信息到store
				commit('SET_ADMININFO', info);
				commit('SET_ADMINROLES', roleList)
				resolve(roleList);
			}).catch((error) => {
				reject(error)
			})

		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
